#!/bin/bash

set -eo pipefail

registry_credentials_available() {
    echo "Checking registry credentials"
    [[ -n "${CI_REGISTRY_USER}" ]] && [[ -n "${CI_REGISTRY_PASSWORD}" ]] && return 0
    return 1
}

login() {
    echo "Logging into registry"
    registry_credentials_available || return 0
    docker login --username ${CI_REGISTRY_USER} --password ${CI_REGISTRY_PASSWORD} ${CI_REGISTRY}
}

logout() {
    echo "Logging out of registry"
    docker logout ${CI_REGISTRY}
}

pull () {
    echo "Pulling base image"
    registry_credentials_available || return 0
    docker pull ${BUILD_IMAGE} || echo "${BUILD_IMAGE} image is not available. Will not use cache."
}

push () {
    echo "Pushing image"
    registry_credentials_available || return 0
    docker push ${BUILD_IMAGE}
}


build() {
    echo "Building image: ${BUILD_IMAGE}"
    docker build \
           --cache-from ${BUILD_IMAGE} \
           -t ${BUILD_IMAGE} \
           -f ${BUILD_DOCKERFILE} \
           .
}

login
pull
build
push
logout
